import { createStore } from 'vuex'
const setLocalCartList = (state) => {
  const  { cartList } = state
  const cartListString = JSON.stringify(cartList) 
  localStorage.cartList = cartListString
}

const getLocalCartList = () => {
  try {
    return JSON.parse(localStorage.cartList);
  } catch(e) {
    return {}
  }
}
export default createStore({
  state: {
    cartList: getLocalCartList()
        // { shopId: {shopName:'', productList:{ productId: {} }}}
      //第一层级为商铺id
        //第二层是商铺名称和商品列表
        //第二层内容是商品内容以及购物车数量   
  },
  getters: {
  },
  mutations: {
    changeCartItemInfo(state,payload){
      const { shopId,productId,productInfo } = payload
      let shopInfo = state.cartList[shopId] || { shopName: '',productList: {}}
      let product = shopInfo.productList[productId]
      if(!product){ 
        product = productInfo
        product.count = 0
      }
      product.count += payload.num
      if(payload.num > 0) { product.check = true }
      if(product.count < 0) { product.count = 0}
      else if ( product.count > 99 ) { product.count = 99}
      shopInfo.productList[productId] = product
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
      console.log(state.cartList);
    },
    changeCartItemChecked(state,payload){
      const { shopId,productId } = payload
      const product = state.cartList[shopId].productList[productId]
      product.check = !product.check
      setLocalCartList(state)
    },
    cleanCartProducts(state,payload){
      const { shopId } = payload
      state.cartList[shopId].productList = {}
      setLocalCartList(state)
    },
    setCartItemsChecked(state,payload){
      const { shopId } = payload
      const products = state.cartList[shopId].productList
      if(products){
        for(let key in products){
          const product = products[key]
          product.check = true
        }
      }
      setLocalCartList(state)
    },
    changeShopName(state,payload){
      const { shopId,shopName } = payload
      const shopInfo = state.cartList[shopId] || { shopName: '',productList: {}}
      shopInfo.shopName = shopName
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    },
    clearCartData(state,shopId){
      state.cartList[shopId].productList = {}
      
    }
  },
  actions: {
  },
  modules: {
  }
})
